using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

/// <summary>
/// 游戏管理器：控制游戏状态和UI显示
/// </summary>
public class GameManager : MonoBehaviour
{
    [Header("UI设置")]
    [Tooltip("游戏结束面板")]
    [SerializeField] private GameObject gameOverPanel;
    [Tooltip("重启按钮")]
    [SerializeField] private Button restartButton;

    [Header("组件引用")]
    [Tooltip("障碍物生成器")]
    [SerializeField] private ObstacleSpawner obstacleSpawner;
    [Tooltip("玩家控制器")]
    [SerializeField] private PlayerController playerController;

    private void Start()
    {
        // 初始化UI
        if (gameOverPanel != null)
        {
            gameOverPanel.SetActive(false);
        }

        // 添加重启按钮点击事件
        if (restartButton != null)
        {
            restartButton.onClick.AddListener(RestartGame);
        }

        // 获取组件引用（如果没有通过Inspector设置）
        if (playerController == null)
        {
            playerController = GameObject.Find("Player").GetComponent<PlayerController>();
        }
        if (obstacleSpawner == null)
        {
            obstacleSpawner = FindObjectOfType<ObstacleSpawner>();
        }
    }

    private void Update()
    {
        // 检查游戏是否结束
        if (playerController != null && playerController.IsGameOver())
        {
            GameOver();
        }
    }

    /// <summary>
    /// 处理游戏结束
    /// </summary>
    private void GameOver()
    {
        // 显示游戏结束UI
        if (gameOverPanel != null)
        {
            gameOverPanel.SetActive(true);
        }

        // 停止生成障碍物
        if (obstacleSpawner != null)
        {
            obstacleSpawner.StopSpawning();
        }
    }

    /// <summary>
    /// 重启游戏
    /// </summary>
    private void RestartGame()
    {
        // 重新加载当前场景
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);

        
    }
}
